import os
import sys
# celery 根目录
CELERY_BASE_DIR = os.path.dirname(os.path.abspath(__file__))

# 把meiduo_mall目录加入到导包路径
sys.path.insert(0, os.path.join(CELERY_BASE_DIR, '../meiduo_mall'))

import time

from celery import Celery

# 定义celery实例, 需要的参数, 1, 实例名, 2, 任务发布位置, 3, 结果保存位置
app = Celery('mycelery', broker='redis://127.0.0.1:6379/14', backend='redis://127.0.0.1:6379/15')


@app.task
def add(x, y):
    return x + y

@app.task(bind=True)
def send_sms_code(self, mobile, sms_code, time_expire):
    # 发送短信

    # 在方法中导包
    from libs.yuntongxun.sms import CCP
    time.sleep(5)
    ccp = CCP()
    try:
        # 用 res 接收发送结果, 成功是:０，　失败是：－１
        res = ccp.send_template_sms(mobile, [sms_code, time_expire], 1)
    except Exception as e:
        print(e)
        res = -1

    if res == -1:
        # 如果发送结果是 -1  就重试.
        self.retry(countdown=5, max_retries=3, exc=Exception('短信发送失败'))

@app.task(bind=True)
def send_verify_email(self, subject, message, from_email, email):
    # 发送验证邮件,
    # 主题, 内容, 发件人, 收件人地址
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "meiduo_mall.dev")
    import django
    django.setup()

    from django.core.mail import send_mail

    res = send_mail(subject=subject, message=message, from_email=from_email,
              recipient_list=[email])

    # 返回来发送成功的数量,  只能是 0 (失败了)或者 1(成功了)

    if res == 0:
        self.retry(countdown=5, max_retries=3, exc=Exception('邮箱验证发送失败'))
    else:
        return res

# 命令行, 进入celery_task目录
# 执行: celery -A main worker -l info
